package com.site.action.backend.system;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.site.dto.backend.system.UsersBizBean;
import com.site.service.backend.system.UsersService;
import com.site.util.CodeUtils;
import com.site.util.StringUtils;
import com.site.util.base.action.BackendBaseAction;
import com.site.util.base.service.BaseService;
import com.site.util.constant.Constants;
import com.site.util.exception.ApplicationException;

/**
 * 系统用户管理
 * @author jack 2012-10-09
 *
 */
public class UserAction extends BackendBaseAction {
	
	Log	log = LogFactory.getLog(UserAction.class);
	
	private static final long serialVersionUID = 1L;
	
	private UsersBizBean usersBizBean;
	
	private UsersService usersService;
	
	private ResultBean resultBean = new ResultBean();
	
	private List<UsersBizBean> usersBizBeanList;
	/*
	 * 锁定，解锁 id 字符串
	 * 格式：123,123,1233
	 */
	private String idsStr;
	
	public String getIdsStr() {
		return idsStr;
	}
	public void setIdsStr(String idsStr) {
		this.idsStr = idsStr;
	}
	public List<UsersBizBean> getUsersBizBeanList() {
		return usersBizBeanList;
	}
	public void setUsersBizBeanList(List<UsersBizBean> usersBizBeanList) {
		this.usersBizBeanList = usersBizBeanList;
	}
	public UsersBizBean getUsersBizBean() {
		return usersBizBean;
	}
	public void setUsersBizBean(UsersBizBean usersBizBean) {
		this.usersBizBean = usersBizBean;
	}
	public UsersService getUsersService() {
		return usersService;
	}
	@Resource
	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}
	/**
	 * 分页查询所有用户信息
	 * @return
	 */
	public String getUserList(){
		if(queryPage == null) {
			initPagination();
		}
		usersBizBeanList = usersService.getUserList(usersBizBean, queryPage);
		return "getUserList";
	}
	
	/**
	 * 增加系统用户页面
	 * @return
	 */
	public String getUserAdd(){
		return "getUserAdd";
	}
	/**
	 * 增加系统用户
	 * @return
	 */
	public String userAdd() throws ApplicationException,Exception {
		
		// 数据验证
		if(addcheckUser()||uniqueCheckUser()){
			response.getWriter().write(JSONObject.toJSONString(resultBean));
			return null;
		}
		
		try {
			//MD5加密
			String psw = CodeUtils.md5Digest(usersBizBean.getPassWord());
			usersBizBean.setPassWord(psw);
			// 增加用户默认为未锁定
			usersBizBean.setStatus(Constants.COMM_N);
			usersBizBean.setCreatedUser(getCurrentUser().getUserName());
			usersBizBean.setUpdatedUser(getCurrentUser().getUserName());
			usersService.execute(usersBizBean, BaseService.COMMAND_SAVE);
		} catch (Exception e) {
			log.error("新建用户失败！");
			e.printStackTrace();
		}
		response.getWriter().write(JSONObject.toJSONString(resultBean));
		return null;
	}
	
	/**
	 * 添加用户时的唯一验证
	 */
    private boolean uniqueCheckUser() {
    	boolean result = false;
		if(usersService.getUserByNameLower(usersBizBean.getUserName())!=null){
			resultBean.setUserName("该用户已存在！");
			result = true;
		}
		return result;
	}
	/**
	 * 添加时的非空验证
	 * @return
	 */
	public boolean addcheckUser(){
		boolean result = false;
		if(usersBizBean.getUserName()== null||"".equals(usersBizBean.getUserName())){
			resultBean.setUserName("登陆名不能为空！");
	        result = true;
		}
		if(usersBizBean.getPassWord()==null||"".equals(usersBizBean.getPassWord())){
			resultBean.setPassWord("密码不能为空！");
	        result = true;
		}
		if(usersBizBean.getConfirmPasswrok()==null||"".equals(usersBizBean.getConfirmPasswrok())){
			resultBean.setConfirmPasswrok("确认密码不能为空！");
			result = true;
		}
		if(usersBizBean.getPassWord()!=null&&!"".equals(usersBizBean.getPassWord())&& usersBizBean.getConfirmPasswrok()!=null&&!"".equals(usersBizBean.getConfirmPasswrok())){
			if(!usersBizBean.getPassWord().equals(usersBizBean.getConfirmPasswrok())){
				resultBean.setConfirmPasswrok("两次密码不一致！");
				result = true;
			}
		}
		if(usersBizBean.getRealName()==null||"".equals(usersBizBean.getRealName())){
			resultBean.setRealName("真实姓名不能为空！");
			result = true;
		}
		 
		if(usersBizBean.getEmail()!=null&&!"".equals(usersBizBean.getEmail().trim())){
			if(mailCheck(usersBizBean.getEmail())==false){
				resultBean.setEmail("请输入正确格式的邮箱！");
				result = true;
			}
			
		}
		return result;
	}
	/**
	 * 判断邮箱是否合法
	 */
	 public boolean mailCheck(String str){
		 String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		 Pattern regex = Pattern.compile(check);
		 Matcher matcher = regex.matcher(str);
		 boolean isMatched = matcher.matches();
		 return isMatched;
	 }
	 
    /**
     * 删除系统用户
     * @return
     */
    public String userDelete(){
    	
    	try {
    		if(null != usersBizBeanList && usersBizBeanList.size() > 0) {
        		String realname = (String)usersService.execute(usersBizBeanList, BaseService.COMMAND_DELETE);
        		super.setParams(realname);
        		super.setMessageID("SYS_MSG_00022");
        	} else {
        		log.info("编号为空。。。。。");
				super.setMessageID("SYS_MSG_00026");
        	}
    		
    	} catch(Exception e) {
    		super.setMessageID("SYS_MSG_00026");
    		e.printStackTrace();
    	}
    	
    	super.setBackurl(request.getContextPath() + "/system/userAction!getUserList.do");
		return "toMessage";
    }
    
    /**
     * 获得系统用户修改页面
     * @return
     */
    public String getUserEdit() throws Exception {
    	if(null != usersBizBean && usersBizBean.getUserId() != null ){
    		usersBizBean = usersService.getUserById(usersBizBean.getUserId());
    		if(null != usersBizBean){
    			usersBizBean.setConfirmPasswrok(usersBizBean.getPassWord());
    		}
    		response.getWriter().write(JSONObject.toJSONString(usersBizBean));
    	} 
    	return null;
    }
    
    /**
     * 修改系统用户
     * @return
     */
    public String userEdit() throws Exception {
    	try {
    		// 数据验证
    		if(editCheckUser()){
    			returnClientJSON(resultBean);
    			return null;
    		}
    		if(null != usersBizBean) {
    			usersBizBean.setUpdatedUser(getCurrentUser().getUserName());
    			//MD5加密
    			String psw = CodeUtils.md5Digest(usersBizBean.getPassWord());
    			usersBizBean.setPassWord(psw);
        		usersService.execute(usersBizBean, BaseService.COMMAND_UPDATE);
        	} else {
        		log.info("编号为空。。。");
        	}
    	} catch(Exception e) {
    		log.info("修改用户异常。。。");
    		e.printStackTrace();
    	}
    	returnClientJSON(resultBean);
    	return null;
    }
    /**
     * 编辑时的验证
     * @return
     */
	private boolean editCheckUser() {
		boolean result = false;
		if(usersBizBean.getUserName()== null||"".equals(usersBizBean.getUserName())){
			resultBean.setUserName("用户名不能为空！");
	        result = true;
		}
		if(usersBizBean.getPassWord()==null||"".equals(usersBizBean.getPassWord())){
			resultBean.setPassWord("密码不能为空！");
	        result = true;
		}
		if(usersBizBean.getRealName()==null||"".equals(usersBizBean.getRealName())){
			resultBean.setRealName("真实姓名不能为空！");
			result = true;
		}
		if(usersBizBean.getEmail()!=null&&!"".equals(usersBizBean.getEmail().trim())){
			if(mailCheck(usersBizBean.getEmail())==false){
				resultBean.setEmail("请输入正确格式的邮箱！");
				result = true;
			}
			
		}
		return result;
	}
	
	/**
	 * 锁定
	 * @return
	 */
	public String disabled() throws Exception{
		try {
			if(null != idsStr && idsStr.length() > 0){
				usersService.execute(idsStr, "disabled");
				log.info("锁定成功!");
				resultBean.setMessage("用户锁定成功!");
			} else {
				resultBean.setMessage("用户解锁失败，请于管理员联系！");
			}
		} catch (ApplicationException e) {
			resultBean.setMessage("用户锁定失败，请于管理员联系！");
			throw (e);
		}
		response.getWriter().write(JSONObject.toJSONString(resultBean));
		return null;
	}
	
	/**
	 * 解锁
	 * @return
	 */
	public String enabled()throws Exception{
		try {
			if(null != idsStr && idsStr.length() > 0){
				usersService.execute(idsStr, "enabled");
				log.info("解锁成功!");
				resultBean.setMessage("用户解锁成功!");
			} else {
				resultBean.setMessage("用户解锁失败，请于管理员联系！");
			}
		} catch (ApplicationException e) {
			resultBean.setMessage("用户解锁失败，请于管理员联系！");
			throw (e);
		}
		response.getWriter().write(JSONObject.toJSONString(resultBean));
		return null;
	}
	
	/**
	 *获得密码修改页面 
	 * @return
	 */
	public String getChangePassword(){
		return "getChangePassword";
	} 
	/**
	 * 密码修改
	 * @return
	 * @throws Exception 
	 */
	public String changePassword() throws Exception{
		if(check()){
			return "getChangePassword";
		}
		
		try{
			String securedpwd = CodeUtils.md5Digest(usersBizBean.getConfirmPasswrok());
			usersBizBean.setPassWord(securedpwd);
			usersBizBean.setUpdatedUser(this.getCurrentUser().getUserName());
			usersService.execute(usersBizBean, BaseService.COMMAND_UPDATE);
			super.setMessageID("SYS_MSG_00031");
		} catch (Exception e) {
			super.setMessageID("SYS_MSG_00026");
		}
		request.getSession().invalidate();
		super.setBackurl(request.getContextPath() + "/user/loginAction!login.do");
		return "toMessage";
	}
	/**
	 * 密码修改检查
	 * @return
	 * @throws Exception 
	 */
	private boolean check() throws Exception{
		boolean result = false;
		if(usersBizBean != null && StringUtils.isEmpty(usersBizBean.getPassWord())){
			this.addFieldError("passWord", "旧密码不能为空！");
			result = true;
		} else {
			UsersBizBean vo = (UsersBizBean)usersService.loadUserByUsername(this.getCurrentUser().getUserName());
			String securedpwd = CodeUtils.md5Digest(usersBizBean.getPassWord());
			// 输入的密码与数据库的密码是否相同
			if (!vo.getPassWord().trim().equals(securedpwd)) {
				this.addFieldError("passWord", "旧密码错误！");
				result = true;
			}
		}
		if(usersBizBean != null && StringUtils.isEmpty(usersBizBean.getConfirmPasswrok())) {
			this.addFieldError("confirmPasswrok", "新密码不能为空！");
			result = true;
		}
		return result;
	}
	/**
	 * 返回到前端页面的提示信息
	 * @author Lee
	 *
	 */
	public class ResultBean {
		
		private String userName;
		private String passWord;
		private String confirmPasswrok;
		private String realName;
		private String email;
		/*
		 * 错误提示
		 */
		private String message;
		
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
		public String getPassWord() {
			return passWord;
		}
		public void setPassWord(String passWord) {
			this.passWord = passWord;
		}
		public String getConfirmPasswrok() {
			return confirmPasswrok;
		}
		public void setConfirmPasswrok(String confirmPasswrok) {
			this.confirmPasswrok = confirmPasswrok;
		}
		public String getRealName() {
			return realName;
		}
		public void setRealName(String realName) {
			this.realName = realName;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
	}
}
